/**
 * 表单展示页--选择参照页面
 */
mini.parse();
// console.log(mTableName);
var datagrid = mini.get("datagrid1");
var grid = mini.get("grid1");
var formListId;
// console.log(cTableName);
var data5=[];   //创建一个空的新数组
var data6=[];
var idxr;
var girdxr;

function SetData(formListId,data) {
    window.fname=mini.clone(formListId);
    window.ruleId=mini.clone(data);
    formListId = formListId;

    //主表加载
    console.log(formListId, 'formListId');
    $.ajax({
        type : 'POST',
        url : ajaxUrl + "/formltems/findByMtableColumn.do?formListId="+formListId,
        dataType : 'json',
        contentType : "application/json",
        success : function(data) {
            console.log(data);//列
            var data=data.data;
            console.log(data);
            var data=JSON.parse(data);
            console.log(data);
            datagrid.set({
                columns: data
            })
            $.ajax({
                type : 'POST',
                url : ajaxUrl + "/formltems/findByMtableDb.do?formListId="+formListId,
                dataType : 'json',
                contentType : "application/json",
                success : function(data) {
                    console.log(data,'主表数据');//数据
                    datagrid.setData(data.data);
                    window.cTableName=data.cTableName;
                    console.log( window.cTableName);
                    console.log(typeof window.cTableName);
                },
                error : function(jqXHR, textStatus, errorThrown) {
                }
            })
            //子表加载

            $.ajax({
                url : ajaxUrl + "/rule/findTableNameByFormlistId.do?formListId="+formListId,
                type: "post",

                success: function(data){
                    console.log(data);
                    create_tab(data.data);
                    create_table(data.data);

                },
                error : function(data){
                    alert("失败")
                }
            });
        },
        error : function(jqXHR, textStatus, errorThrown) {

        }
    })
    return formListId;
}
console.log(formListId);

//当grid触发选择事件时
function select(e) {
    console.log(e.sender);
    console.log(e.record);
    var tabs = mini.get("tab2s");

    if(tabs==undefined){
        var cTabelName=null;
    }else {
        var nowTab = tabs.getActiveTab();
        console.log(nowTab);
        var cTabelName=nowTab.name;
        if(e.record){
            mTableId=e.record[window.cTableName+"_id"];
            console.log(mTableId);
            //数据
            $.ajax({

                url: ajaxUrl + "/rule/findByTabelName.do",
                type: "post",

                traditional: true,
                data: {
                    fromlistId:  window.fname,     //主表fromlistId
                    id: mTableId,                   //主表id
                    cTabelName:cTabelName          //子表name
                },
                success: function(data){
                    console.log(data,'子表数据');
                    data.data.forEach(function (item) {
                        data5.push(item)
                    })
                    // console.log(data5);
                    //
                    // var hash={};
                    // if(window.cTableName+"_id"){
                    // data5=data5.reduce(function (item,next) {
                    //         hash[next[cTableName+"_id"]]?'':hash[next[cTableName+"_id"]]=true&&item.push(next);
                    //         return item
                    // },[])
                    // }
                    console.log(data5);
                    data10=mini.clone(data5)
                    // var girdxr=mini.get(idxr);
                    girdxr.setData(data5);
                    girdxr.selects(data5,true);
                },
                error : function(data){
                    mini.alert('获取失败')
                }
            });
        }
    }
}
//当行取消选中时
function deselect(e) {
    console.log(e.sender);
    console.log(e.record);
    var row7=[];
    console.log("quxiaoxuanzhong");

    var row4=datagrid.getSelecteds();  //主表的选中行
    if(girdxr&&girdxr!=undefined){
        var row5=girdxr.getData();         //子表的所有行数据
    }
    if(row5&&row5[0]&&row5[0]!=undefined){
        row4.forEach(function (item) {    //主表打勾的数据
            var row5=girdxr.findRow(function(row5){          //子表查找匹配的数据
                if(item[window.cTableName+"_id"]==row5[window.cTableName+"_id"]) {
                    console.log(row5);
                    row7.push(row5);
                } //子表的ID等于主表时返回出来

                return true;
            });

        })
        girdxr.setData("");
        data5=[];              //因为选择主表渲染子表那的存储数据还是很多所以先清空，然后给它赋予应该还剩下的数据
        data5=row7;                //让他等于应该渲染的数据
        girdxr.setData(row7);      //子表渲染的数据
        girdxr.selects(row7,true);
    }

}
//确定按钮
function onOk(e) {
    console.log(e);
    row1=datagrid.getSelecteds();//获得主表的行数据
    console.log(row1);
    if(idxr!=undefined){      //当有子表的情况下
        // var grid=mini.get(idxr);    //获得子表的ID
        row2=girdxr.getSelecteds();  //获得子表的行数据
        console.log(row2);
    }else{
        row2={}
    }


    if(row2==undefined||row1==undefined){    //当有子表的时候不能只选一个，必须主表子表全选，否则弹出警告
        mini.alert("请选择数据!!!")
    }else {
        // row3=eval('('+(JSON.stringify(row[0])+JSON.stringify(row2[0])).replace(/}{/,',')+')');  //把主表和子表拼接在一起，成为一个大{}
        // console.log(row3);
        // row3=JSON.stringify(row3);    //把主表换成字符串
        CloseWindow("ok");   //状态"ok"
        console.log(window.ruleId);
    }

}
//确定按钮之前
function onTableOk() {
    row1=row1;
    stable=row2;
    ruleId= window.ruleId;  //参照ruleId等于全局的ruleId
    return {row1,stable,ruleId};    //映出row3和ruleId，当子页面消失调用

}
var rowarr=[];
//取消按钮
function onCancel(e) {
    CloseWindow("cancel");
}

function CloseWindow(action) {

    if (window.CloseOwnerWindow)
        return window.CloseOwnerWindow(action);
    else
        window.close();
}

var select_data = [];
function onSelectAll(e) {

}
//生成动态tab
function create_tab(arr_tab) {
    console.log(arr_tab, 'arr_tab分组后');

    var div='' ;

    for (var j =0;j< arr_tab.length ;j++) {
        var ctr=arr_tab[j].cTableName+'_zd';   //拼一个变量，下面用
        var ctrd=arr_tab[j][ctr][j].tab_id;
        div = "<div  name='"+arr_tab[j].cTableName+"' title='"     //外面的包裹的
            + arr_tab[j].cTableNameCH+ "'> </div>\n" + div;

        var $clone = "<div id='tab2s'  onactivechanged=\"activechanged\"  class='mini-tabs' activeIndex='0'>\n"     //包裹加的tab
            + div + "</div>";
    }

    $('#tabs1').append($clone);           //获取html上的id然后append添加克隆那些
    mini.parse();
    $('#tabs1').css({
        width:900,
        height: 250,

    });

}
//生成表格
function create_table(arr_tab) {

    for (var j=0; j < arr_tab.length ; j++) {

        var ids = arr_tab[j].cTableName + "_zd";   //提前var一个ctableName
        var cols = JSON.parse(arr_tab[j][ids][j].gridColumns);   //把要用的数据转化成json
        console.log(cols);
        cols.unshift({type:"checkcolumn"});
        var  colss=arr_tab[j].cTableName;
        //grid模板
        var template = ' <div id="' + arr_tab[j][ids][j].c_id + '"   class="mini-datagrid"> </div> '

        var tabs=mini.get("tab2s");    //获取tabs父元素
        console.log(arr_tab[j].cTableName);
        var el=tabs.getTabBodyEl(arr_tab[j].cTableName);  //获取el
        var elId=escapeJquery(el.id);
        // $('#'+elId).css('display','none');
        $('#'+elId).append(template);     //每个页签后添加grid

        var id = arr_tab[j][ids][j].c_id;   //备份grid的ID
        idxr=mini.clone(id);
        console.log(id);

        mini.parse();
        var grid = mini.get(id);
        grid.set({
            url: "",
            columns: cols,
            multiSelect:true,
            allowResize: true,
            allowCellEdit: true,
            allowCellSelect: true,
            cellEditAction: "celldblclick",
            allowRowSelect: true,
            showPager: false,
            editNextOnEnterKey: true,
            editNextRowCell: true,
            showModified: false,
            showHGridLines:true,
            allowCellValid: true,

        });
        console.log(JSON.parse(arr_tab[j][ids][j].gridColumns)[j].iWidth);
        console.log( JSON.parse(arr_tab[j][ids][j].gridColumns)[j].iLabHeight);
        $('#'+elId).css({


        })
        $("#" + id).css({
            width: 1000,
            height: 200,
            "min-height": 70
        });
    }
}
//切换面板时发生的事

function activechanged(e) {
    console.log(e);
    console.log(e.sender);
    console.log(e.tab);
    var id=e.tab.name;
    console.log(id);
    var id2="datagrid_";
    var id3=id2+id;
    var tabs = mini.get("tab2s");

    var nowTab = tabs.getActiveTab();
    console.log(nowTab);
    var cTabelName=nowTab.name;
    girdxr=mini.get(id3);
    // girdxr.setData(data10);      //子表渲染的数据
    if(mTableId&&mTableId!=undefined){
        $.ajax({
            url: ajaxUrl + "/rule/findByTabelName.do",
            type: "post",

            traditional: true,
            data: {
                fromlistId:  window.fname,     //主表fromlistId
                id: mTableId,                   //主表id
                cTabelName:cTabelName          //子表name
            },
            success: function(data){
                console.log(data,'子表数据');
                var data=data.data;
                girdxr.setData(data);

            },
            error : function(data){
                mini.alert('获取失败')
            }
        });
    }


}

// jq id含有特殊字符的转义
function escapeJquery(srcString) {
    // 转义之后的结果
    var escapseResult = srcString;

    // javascript正则表达式中的特殊字符
    var jsSpecialChars = ["\\", "^", "$", "*", "?", ".", "+", "(", ")", "[",
        "]", "|", "{", "}"];

    // jquery中的特殊字符,不是正则表达式中的特殊字符
    var jquerySpecialChars = ["~", "`", "@", "#", "%", "&", "=", "'", "\"",
        ":", ";", "<", ">", ",", "/"];

    for (var i = 0; i < jsSpecialChars.length; i++) {
        escapseResult = escapseResult.replace(new RegExp("\\"
            + jsSpecialChars[i], "g"), "\\" + jsSpecialChars[i]);
    }

    for (var i = 0; i < jquerySpecialChars.length; i++) {
        escapseResult = escapseResult.replace(new RegExp(jquerySpecialChars[i],
            "g"), "\\" + jquerySpecialChars[i]);
    }

    return escapseResult;
}